﻿/*======================================================================
== Copyright : BlueCurve (c)
== Licence   : Gnu/GPL v2.x
== Author    : Teddy Albina
== Email     : bluecurveteam@gmail.com
== Web site  : http://www.codeplex.com/BlueCurve
========================================================================*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using BlueCurve.Common.Application;
using System.Diagnostics;

namespace ShareCrawler
{
    class Program : BlueCurve.Common.InteractiveConsole.BaseConsole
    {
        /// <summary>
        /// Class de traitement des fichiers trouvés
        /// </summary>
        private static DataTreatment s_treatment { get; set; }
        /// <summary>
        /// Instance de la class de parcours des partages de fichiers
        /// </summary>
        private static DriveAccess s_drive = new DriveAccess();
        /// <summary>
        /// Thread de traitement des fichier téléchargé
        /// </summary>
        private static Thread _s_treatment { get; set; }
        /// <summary>
        /// Thread de la console interactive
        /// </summary>
        private static Thread s_console { get; set; }

        static void Main(string[] args)
        {
            s_treatment = new DataTreatment(s_drive);
            s_console = new Thread(new ThreadStart(new Program().Run));
            s_console.Start();
            
            // Recherche des documents à mettre à jour
            List<SelectAllDataInShareCrawlerCacheResult> _datas;
            using (ShareCrawlerdbDataContext db = new ShareCrawlerdbDataContext())
            {
                _datas = db.SelectAllDataInShareCrawlerCache().ToList();
            }

            _datas.ForEach(
                delegate(SelectAllDataInShareCrawlerCacheResult res)
                {
                    ThreadPool.QueueUserWorkItem(new WaitCallback(s_treatment.DoWork2), res.URI);
                });
            
            // Récupération des partages de fichiers à scanner
            List<SelectAllDataInShareToScanResult> _shares;
            using (ShareCrawlerdbDataContext db = new ShareCrawlerdbDataContext())
            {
                _shares = db.SelectAllDataInShareToScan().ToList();
            }

            List<string> boot = new List<string>();
            _shares.ForEach(
                delegate(SelectAllDataInShareToScanResult res)
                {
                    boot.Add(res.PATH);
                });

#if DEBUG
            s_drive.GetAllFiles(new string[] { @"F:\" });
#else
            s_drive.GetAllFiles(boot.ToArray());
#endif
        }

        /// <summary>
        /// Arrete l'application
        /// </summary>
        private void StopApplication()
        {
            s_treatment.IsStop = true;
            while (s_treatment.AliveThreads > 0) { Thread.Sleep(150); }

            if (_s_treatment.ThreadState == System.Threading.ThreadState.Running)
                _s_treatment.Abort();

            s_drive.IsStop = false;
            
            // Suicide de l'application
            Process.GetCurrentProcess().Kill();
        }

        /// <summary>
        /// Relance l'application
        /// </summary>
        private void RestartApplication()
        {
            s_treatment.IsStop = true;
            while (s_treatment.AliveThreads > 0) { Thread.Sleep(150); }

            if (_s_treatment.ThreadState == System.Threading.ThreadState.Running)
                _s_treatment.Abort();

            s_drive.IsStop = false;

            // Enregistre l'application pour le redemarrage
            Restart.RestartApplication(string.Concat(System.Diagnostics.Process.GetCurrentProcess().ProcessName, ".exe"));
            // Suicide de l'application
            Process.GetCurrentProcess().Kill();
        }


        /// <summary>
        /// Commandes de la console
        /// </summary>
        protected override void LoadCommands()
        {
            this.Commands.Add("-stop", new Dictionary<Action, string>()
            { 
                { () => StopApplication(), "Arrete l'application" }
            });
            this.Commands.Add("-restart", new Dictionary<Action, string>()
            {
                { () => RestartApplication(), "Relance l'application" }
            });
        }

        /// <summary>
        /// Retourne le nom de l'application
        /// </summary>
        public override string Name
        {
            get { return "BlueCurve Share Crawler"; }
        }
    }
}
